const Service = require('egg').Service;

class AnnouncementService extends Service {
  // 创建公告
  async create(announcementData) {
    const { ctx } = this;

    // 检查管理员是否存在
    const admin = await ctx.model.Admin.findByPk(announcementData.admin_id);
    if (!admin) {
      throw new Error('管理员不存在');
    }

    const announcement = await ctx.model.Announcement.create({
      ...announcementData,
      created_at: new Date(),
      updated_at: new Date()
    });

    // 返回公告信息
    const { createdAt, updatedAt, ...announcementInfo } = announcement.toJSON();
    return announcementInfo;
  }

  // 获取公告列表（分页）
  async getAnnouncements(query) {
    const { ctx, app } = this;
    const { page = 1, pageSize = 10, title, start_date, end_date } = query;
    
    // 获取 Sequelize 操作符
    const Op = app.Sequelize.Op;

    const where = {};
    if (title) {
      where.title = { [Op.like]: `%${title}%` };
    }
    if (start_date && end_date) {
      where.created_at = {
        [Op.between]: [new Date(start_date), new Date(end_date)]
      };
    }

    const options = {
      where,
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['created_at', 'DESC']],
      include: [{
        model: ctx.model.Admin,
        as: 'admin',
        attributes: ['admin_id', 'admin_name', 'email']
      }]
    };

    const { count, rows } = await ctx.model.Announcement.findAndCountAll(options);

    return {
      list: rows,
      pagination: {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: count,
        totalPages: Math.ceil(count / pageSize)
      }
    };
  }

  // 根据ID获取公告详情
  async getAnnouncementById(announcementId) {
    const { ctx } = this;

    const announcement = await ctx.model.Announcement.findByPk(announcementId, {
      include: [{
        model: ctx.model.Admin,
        as: 'admin',
        attributes: ['admin_id', 'admin_name', 'email']
      }]
    });

    if (!announcement) {
      throw new Error('公告不存在');
    }

    return announcement;
  }

  // 更新公告信息
  async updateAnnouncement(announcementId, updateData) {
    const { ctx, app } = this;

    // 检查公告是否存在
    const announcement = await ctx.model.Announcement.findByPk(announcementId);
    if (!announcement) {
      throw new Error('公告不存在');
    }

    // 如果更新管理员ID，检查管理员是否存在
    if (updateData.admin_id && updateData.admin_id !== announcement.admin_id) {
      const admin = await ctx.model.Admin.findByPk(updateData.admin_id);
      if (!admin) {
        throw new Error('管理员不存在');
      }
    }

    // 更新公告信息
    await announcement.update({
      ...updateData,
      updated_at: new Date()
    });

    // 返回更新后的公告信息
    const updatedAnnouncement = await ctx.model.Announcement.findByPk(announcementId, {
      include: [{
        model: ctx.model.Admin,
        as: 'admin',
        attributes: ['admin_id', 'admin_name', 'email']
      }]
    });

    return updatedAnnouncement;
  }

  // 删除公告
  async deleteAnnouncement(announcementId) {
    const { ctx } = this;

    const announcement = await ctx.model.Announcement.findByPk(announcementId);
    if (!announcement) {
      throw new Error('公告不存在');
    }

    await announcement.destroy();
    return true;
  }

  // 获取最新公告（用于前端展示）
  async getLatestAnnouncements(limit = 5) {
    const { ctx } = this;

    const announcements = await ctx.model.Announcement.findAll({
      limit: parseInt(limit),
      order: [['created_at', 'DESC']],
      attributes: [
        'announcement_id',
        'title',
        'content',
        'created_at'
      ]
    });

    return announcements;
  }

  // 获取公告统计信息
  async getAnnouncementStats() {
    const { ctx, app } = this;
    
    // 获取 Sequelize 操作符
    const Op = app.Sequelize.Op;

    const total = await ctx.model.Announcement.count();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayCount = await ctx.model.Announcement.count({
      where: {
        created_at: {
          [Op.gte]: today
        }
      }
    });

    return {
      total,
      todayCount
    };
  }
}

module.exports = AnnouncementService;